<template>
  <div class="main">
    <!-- 检索区,查询表单 -->
    <div class="search-container">
      <div class="search" style="padding: 5px">
        <!-- 全文检索 -->
        <el-form-item style="width: 100%" prop="globalSearch">
          <el-input
              placeholder="支持标题、摘要、作者检索"
              v-model="pm.globalSearch"
              class="search-input"
          />
        </el-form-item>
        <!-- 按钮 -->
        <el-button
            color="#409EFF"
            plain
            :icon="Search"
            @click="search"
            class="search-button"
        >
          查询
        </el-button>
      </div>
    </div>
<!--    TODO:检索区-->
    <!-- 操作区 -->
    <div class="action">
      <el-button
          color="#409eff"
          plain
          :icon="Plus"
          @click="add"
          style="margin-left: 10px"
      >新增</el-button
      >
      <el-button type="danger" plain :icon="Delete" @click="deleteAll"
      >批量删除</el-button
      >
    </div>

    <div class="data">
<!--      数据展示-->
      <div class="literature-container">
        <div class="literature-grid">
          <el-card
              v-for="item in tableData"
              :key="item.literatureId"
              class="literature-card compact"
          >
            <div class="literature-header">
              <div class="title-section">
                <h3 class="title">
                  <el-link type="primary" :underline="false" style="font-size: large">
                    {{ item.title }}
                  </el-link>
                </h3>
              </div>
              <div class="header-meta">
                <span class="author">{{ item.author }}</span>
                <span class="divider">|</span>
                <span class="publication-year">{{ item.publicationYear }}</span>
              </div>
            </div>

            <div class="literature-body">
              <div class="second-layer">
                <div class="keywords">
                  <el-tag
                      v-for="(keyword, index) in item.keywords.split(',')"
                      :key="index"
                      size="large"
                      class="keyword-tag"
                  >
                    {{ keyword.trim() }}
                  </el-tag>
                </div>
<!--                经过出现小手-->
                <div class="literature-type">
                  <el-tag
                      size="small"
                      type="success"
                      class="type-tag"
                  >
                    {{ item.literatureType }}
                  </el-tag>
                </div>
              </div>
<!--摘要部分-->
              <el-tooltip
                  :content="item.abstractz"
                  placement="top"
                  :show-after="100"
                  effect="light"
                  max-width="300"
                  popper-class="abstract-tooltip"
              >
                <div class="abstract">
                  {{ item.abstractz }}
                  <el-icon class="expand-icon" :size="14">
                    <More />
                  </el-icon>
                </div>
              </el-tooltip>

              <div class="literature-actions">
                <div class="stat-item">
                  <div
                      class="icon-wrapper"
                      @click="toggleLike(item)"
                  >
                    <el-icon :color="item.isLiked ? '#f5a623' : '#999'">
                      <Star />
                    </el-icon>
                    <span class="stat-count">{{ item.likeCount }}</span>
                  </div>
                  <div
                      class="icon-wrapper"
                      @click="toggleCollect(item)"
                  >
                    <el-icon :color="item.isCollected ? '#1296db' : '#999'">
                      <Collection />
                    </el-icon>
                    <span class="stat-count">{{ item.citationCount }}</span>
                  </div>
                  <el-tooltip
                      :content="getFileNameFromPath(item.filePath)"
                      placement="top"
                      effect="light"
                  >
                    <div
                        class="icon-wrapper"
                        @click="downloadDocument(item)"
                    >
                      <el-icon color="#409eff">
                        <Download />
                      </el-icon>
                      <span class="stat-count">下载</span>
                    </div>
                  </el-tooltip>
                  <el-button
                      type="primary"
                      :icon="Edit"
                      plain
                      size="small"
                      @click="edit(item)"
                  >
                    编辑
                  </el-button>
                  <el-button
                      type="danger"
                      :icon="Delete"
                      plain
                      size="small"
                      @click="removeById(item)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-pageNum="pageInfo.pageNum"
            v-model:pageNum-size="pageInfo.size"
            :pageNum-sizes="[10, 15, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
            background
            @change="paginate"
        />
      </div>
    </div>
  </div>
<!--  新增或删除操作-->
  <el-dialog
      v-model="show"
      :title="title"
      width="800"
      draggable
      :close-on-click-modal="false"
      @close="close"
  >
    <el-form ref="sfRef" :model="pfm" label-width="100" style="width: 100%; margin: 0 auto;">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
              label="文献标题"
              prop="title"
              :rules="[
              {
                required: true,
                message: '请输入植文献标题',
                trigger: 'blur',
              },
            ]"
          >
            <el-input v-model="pfm.title" />
          </el-form-item>

          <el-form-item label="作者名称:" prop="author">
            <el-input v-model="pfm.author" />
          </el-form-item>

          <el-form-item label="出版年份:" prop="isRare">
<!--           出版年份设置为:下拉框-->
            <el-select v-model="pfm.publicationYear" placeholder="请选择出版年份">
              <el-option
                  v-for="item in publicationYearOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文献类型:" prop="literatureType">
            <!--           文件类型设置为:下拉框-->
            <el-select v-model="pfm.literatureType" placeholder="请选择文献类型">
              <el-option
                  v-for="item in literatureTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="关键词:" prop="keywords">
            <el-input type="text" v-model="pfm.keywords" />
          </el-form-item>
        </el-col>
<!--        摘要，输入框的高度增高一点-->
        <el-col :span="24">
        <el-form-item label="摘要:" prop="abstractz" >
          <el-input type="textarea" v-model="pfm.abstractz"  />
        </el-form-item>
      </el-col>
      </el-row>
      <!--        下载附件-->
      <el-form-item label="文献附件:" prop="filePath">
        <el-upload
            class="literature-uploader"
            :action="uploadUrl"
            :show-file-list="true"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :limit="1"
            :file-list="fileList"
        >
          <template #trigger>
            <el-button type="primary" plain>选择文件</el-button>
          </template>

          <template #tip>
            <div class="upload-tip">
              仅支持PDF、DOC、DOCX格式，大小不超过50MB
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form >
    <!-- 对话框按钮，#插槽: 组件空出来，允许用户更改组件内容。由组件使用者定义 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script setup>
import literatureApi from "@/api/LiteratureApi.js";
import { ref, watch } from 'vue'
import { onMounted, toRaw, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Refresh,
  Plus,
  More
} from "@element-plus/icons-vue";

//当组件挂载结束之后调用
onMounted(() => {
  search();
  document.title = "文献表型数据管理系统";
});

//响应式对象
const tableData = ref([]);
function paginate() {
  search();
}

// 下载提示按钮
const getFileNameFromPath = (filePath) => {
  if (!filePath) return '';
  // 先获取最后一个斜杠后的文件名
  const fullFileName = filePath.split('/').pop();
  // 如果文件名包含时间戳格式（14位数字加下划线），则去除
  return fullFileName.replace(/^\d{14}_/, '');
}


// 分页信息
const pageInfo = ref({
  pageNum: 1,
  size: 10,
  total: 0,
});

// 当页码和页码大小改变时触发

function search() {
  let params = pm.value; //查询条件
  literatureApi
      .findAll(pageInfo.value.pageNum, pageInfo.value.size, params)
      .then((result) => {
        if (result.code == 200) {
          tableData.value = result.data.records;
          pageInfo.value.total = result.data.total;
          pageInfo.value.pageNum = result.data.pages;
          pageInfo.value.size = result.data.size;
        }
      });
}

// 搜索条表单双向数据绑定
const pm = ref({
  literatureId: "",
  title: "",
  author: "",
  publicationYear:"",
  literatureType: "",
  abstractz: ""
});

// // 表单实例的引用
let searchFromRef;
function resetSearch() {
  // 重置查询表单
  searchFromRef.resetFields();
}
// 定义表格实例
let tableRef;
//当点击表格时触发
function rowClick(row) {
  tableRef.toggleRowSelection(row);
}

// 删除操作逻辑
function deleteAll() {
  // 从表格中选中的行
  let rows = tableRef.getSelectionRows();
  let ids = []; //id数组
  for (let row of rows) {
    ids.push(row.literatureId);
  }
  //执行删除操作
  deleteById(ids);
}
//根据id数组批量删除
function deleteById(ids) {
  // 判断是否选中了要删除的记录
  if (ids.length == 0) {
    ElMessage({
      message: "请选中要删除的记录！",
      type: "warning",
    });
  } else {
    ElMessageBox.confirm("是否确定删除选中的记录吗？", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      literatureApi
          .removeAll(ids)
          .then((resp) => {
            if (resp.code == 200) {
              ElMessage({
                type: "success",
                message: "删除成功",
              });
              search(); //刷新
            }
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "删除操作取消",
            });
          });
    });
  }
}
//  按id删除
function removeById(row) {
  let plant = toRaw(row);
  deleteById([plant.literatureId]);
}

// 对话框是否显示
const show = ref(false);

// 定义对话框内容
const plainFormModel = ref({
  title: "",
  author: "",
  publicationYear: "",
  literatureType:"",
  abstractz:"",
  keywords: "",
  filePath: "",
});
// 对话框内容别名
const pfm = plainFormModel;

// 对话框标题
const title = ref("新增文献信息");
// 弹出新增
function add() {
  show.value = true;
  title.value = "新增文献信息";
  pfm.value = {
    literatureId: "",
    title: "",
    author: "",
    publicationYear: "",
    literatureType:"",
    abstractz:"",
    keywords: "",
    filePath: "",
  };
}
// 提交表单
function submitForm() {
  let literature = pfm.value;
  if (literature.literatureId !== "" ) {
    //修改
    submitEdit(literature);
  } else {
    //新增
    submitAdd(literature);
  }
}

// 新增逻辑
function submitAdd(literature) {
  literatureApi.save(literature).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "新增成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

let sfRef;
// 关闭对话框，重置表单
function close() {
  sfRef.resetFields();
}

// 修改操作
function edit(row) {
  let plant = toRaw(row);
  // 浅拷贝
  row = Object.assign({}, plant);
  show.value = true;
  title.value = "修改文献信息";
  // 下一个时间滴答中赋值
  nextTick(() => {
    pfm.value = row; //给新增/修改表单赋值
  });
}
// 提交表单执行逻辑
function submitEdit(literature) {
  literatureApi.update(literature).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });

  show.value = false;
}

//表头样式
function headerCellStyle() {
  return {
    background: " #f4f4f5",
    textAlign: "center",
    color: "#909399",
  };
}

// 切换状态
function switchChange2(row) {
  let literature = toRaw(row);
  user.locked = user.locked === true ? 0 : 1;
  literatureApi.updataByState(literature).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });

      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
}

//头像上传成功时的回调函数
function avatarSuccess(resp, file) {
  if (resp.code == 200) {
    pfm.value.imagePath = resp.data;
  }
}
// 点赞
const props = defineProps({
  tableData: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['edit', 'remove'])

const toggleLike = (item) => {
  item.isLiked = !item.isLiked
  item.likeCount += item.isLiked ? 1 : -1
  //   如果isLiKed为1，则提示点赞成功
  if (item.isLiked) {
    ElMessage({
      type: "success",
      message: "点赞成功",
    });
  }else {
    ElMessage({
      type: "info",
      message: "取消点赞",
    });
  }
}

const toggleCollect = (item) => {
  item.isCollected = !item.isCollected
  item.citationCount += item.isCollected ? 1 : -1
//   提示收藏成功
  if (item.isCollected) {
    ElMessage({
      type: "success",
      message: "收藏成功",
    });
  }else {
    ElMessage({
      type: "warning",
      message: "取消收藏",
    });
  }
}

// 下载
const downloadDocument = (item) => {
  // 触发下载逻辑
  console.log(item)
  window.open(item.filePath, '_blank')
  ElMessage.success('开始下载文献')

}
/* 出版年份数组*/
const publicationYearOptions = [
  { value: 2025, label: '2025' },
  { value: 2024, label: '2024' },
  { value: 2023, label: '2023' },
  { value: 2022, label: '2022' },
  { value: 2021, label: '2021' },
  { value: 2020, label: '2020' },
  { value: 2019, label: '2019' },
  { value: 2018, label: '2018' },
  { value: 2017, label: '2017' },
]
/* 文献类型数组 */
const literatureTypeOptions = [
  { value: '期刊', label: '期刊' },
  { value: '硕士论文', label: '硕士论文' },
  { value: '博士论文', label: '博士论文' },
  { value: '书籍', label: '书籍' },
  { value: '会议', label: '会议' },
  { value: '其他', label: '其他' },
]
/* 文件上传组件 */
const uploadUrl = 'http://127.0.0.1:8088/api/file/literatureUpload'
const fileList = ref([])
// 监听 pfm.filePath 的变化
watch(() => pfm.value.filePath, (newPath) => {
  if (newPath) {
    fileList.value = [{
      name: getFileNameFromPath(newPath),
      url: newPath
    }]
  } else {
    fileList.value = []
  }
}, { immediate: true })

// 组件挂载时初始化文件列表
onMounted(() => {
  if (pfm.value.filePath) {
    fileList.value = [{
      name: getFileNameFromPath(pfm.value.filePath),
      url: pfm.value.filePath
    }]
  }
})

const beforeUpload = (rawFile) => {
  const validTypes = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  ]
  const maxSize = 50 * 1024 * 1024 // 50MB

  if (!validTypes.includes(rawFile.type)) {
    ElMessage.error('文件格式仅支持PDF、DOC、DOCX')
    return false
  }

  if (rawFile.size > maxSize) {
    ElMessage.error('文件大小不能超过20MB')
    return false
  }

  return true
}

const handleUploadSuccess = (response) => {
  console.log("上传附件下载结果:", response)
  if (response.code === 200) {
    const fileName = getFileNameFromPath(response.data.filePath)
    fileList.value = [{
      name: fileName,
      url: response.data.filePath
    }]
    pfm.value.filePath = response.data.filePath
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error(response.message || '文件上传失败')
  }
}

const handleUploadError = (error) => {
  ElMessage.error('文件上传失败：' + error)
}
</script>

<style scoped>
/* 检索框部分 */
.search-container {
  width: 100%;
  margin-bottom: 5px;
}

.search {
  display: flex;
  align-items: center;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 24px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-input {
  width: 100%;
  border: none;
  outline: none;
  padding: 3px 12px; /* 增加内边距 */
  font-size: 18px; /* 增加字体大小 */
  height: 46px; /* 设置高度 */
  margin-top: 10px;
}

.search-input:focus {
  border: none;
  outline: none;
}

.search-button {
  height: 46px; /* 与输入框高度一致 */
  border-radius: 0 24px 24px 0;
  border: none;
  color: #fff;
  background-color: #409EFF;
  transition: background-color 0.3s ease;
  margin-left: -1px; /* 确保按钮紧贴输入框 */
}

.search-button:hover {
  background-color: #66b1ff;
}

.search-button:active {
  background-color: #3a8ee6;
}
.demo-form-inline {
  display: flex;
  align-items: center;
}
/* 定义不同状态下的 CSS 类 */
.el-switch-enabled {
  --el-switch-on-color: #13c75b;
  --el-switch-off-color: #13c75b;
}
.el-switch-disabled {
  --el-switch-on-color: #f56c6c;
  --el-switch-off-color: #f56c6c;
}
.pagination {
  margin-top: 20px;
}
.search {
  display: flex;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.search > form .el-form-item {
  flex-grow: 1;
  margin-right: 10px;
  margin-bottom: 0;
}
.action {
  margin-top: 10px;
  width: 100%;
  display: flex;
  padding: 10px 0;
  border-radius: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
}
.dialog-footer {
  margin-top: 20px;
}
.data {
  margin-top: 5px;
  padding: 15px 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}


/* 图片上传部分代码 */
.avatar {
  width: 120px;
  height: 120px;
  border: 1px solid #ccc;
}

.avatar .icon {
  width: 120px;
  height: 120px;
}

.avatar .preview {
  width: 120px;
  height: 120px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
}

.row-avatar {
  width: 50px;
  height: 50px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
  margin: 0 auto;
  border-radius: 50%; /* 设置为50%使头像为圆形 */
  overflow: hidden; /* 防止图片在圆外显示 */
}

/* 表格部分 */
.literature-card.compact {
  margin-bottom: 12px;
  height: 200px;
}

.literature-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: -20px;
}

.header-meta {
  text-align: right;
}

.second-layer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.keywords, .literature-type {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}
/* 展示摘要部分 */
.abstract {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  margin: 8px 0;
  cursor: pointer;
  position: relative;
  padding-right: 20px;  /* 为图标留出空间 */
}

.expand-icon {
  position: absolute;
  right: 0;
  bottom: 0;
  color: #909399;
}

:deep(.abstract-tooltip) {
  max-width: 400px !important;
  line-height: 1.6;
  white-space: pre-wrap;
  padding: 12px 16px;
  font-size: 14px;
}


.literature-actions {
  margin-top: 10px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 13px;
  flex-wrap: wrap;
  margin-top: 10px;
}

.icon-wrapper {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
}

.stat-count {
  font-size: 12px;
  color: #666;
}

.header-meta {
  display: flex;
  align-items: center;
  gap: 5px;
}

.divider {
  color: #ccc;
  margin: 0 5px;
}

.author, .publication-year {
  font-size: 14px;
  color: #666;
}

/* 文件上传逻辑*/
.literature-uploader {
  width: 100%;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

</style>


